package com.rs2lite.loader;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.rs2lite.Constants;
import com.rs2lite.RS2Lite;
import com.rs2lite.utils.Utils;

/**
 * Class ParamaterParser, opens Jagex's non-javascript page and grabs
 * paramaters.
 * 
 * @author Nicole <nicole@rune-server.org>
 * @author popbob This file is protected by The BSD License, You should have
 *         recieved a copy named "BSD License.txt"
 */

public class ParamaterParser {
	
	private Pattern pattern = Pattern.compile("src\\=\"(.*?)\"");

	private ArrayList<String> lines = new ArrayList<String>();

	private HashMap<String, String> params = new HashMap<String, String>();

	public ParamaterParser() {
		try {
			readPage(new URL(Constants.GAME_URL));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void readPage() throws MalformedURLException {
		readPage(new URL(RS2Lite.url));
	}

	public String parseURL() {
		for (String line : lines) {
			Matcher matcher = pattern.matcher(line);
			if(matcher.find()) {
				return matcher.group(1);
			}
		}
		return "";
	}

	public void readPage(URL url) {
		try {
			URLConnection connection = url.openConnection();
			connection
					.addRequestProperty(
							"Accept",
							"text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
			connection.addRequestProperty("Accept-Charset",
					"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			connection.addRequestProperty("Accept-Encoding", "gzip,deflate");
			connection.addRequestProperty("Accept-Language", "en-gb,en;q=0.5");
			connection.addRequestProperty("Connection", "keep-alive");
			connection.addRequestProperty("Host", "www.runescape.com");
			connection.addRequestProperty("Keep-Alive", "300");
			connection.addRequestProperty("User-Agent",
					Utils.getHttpUserAgent());
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			lines.clear();
			while ((line = reader.readLine()) != null) {
				lines.add(line.trim());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public HashMap<String, String> parseParamaters() {
		Pattern pattern = Pattern
				.compile("<param name=\"?([^\\s]+)\"?\\s+value=\"?([^>]*)\"?>");
		for (String line : lines) {
			Matcher matcher = pattern.matcher(line);
			if (matcher.matches()) {
				String param_name = Utils.trim(matcher.group(1), '\"');
				String param_value = Utils.trim(matcher.group(2), '\"');
				params.put(param_name, param_value);
			}
		}
		if (params.containsKey("haveie6")) {
			params.remove("haveie6");
			params.put("haveie6", "0");
		}
		return params;
	}
}
